/**
 * 加亮颜色
 * @param {string} color 颜色值
 * @param {number} percent 百分比
 * @returns {string} 处理后的颜色值
 */
function lighten(color, percent) {
  const num = parseInt(color.replace('#', ''), 16)
  const amt = Math.round(2.55 * percent)
  const R = (num >> 16) + amt
  const G = ((num >> 8) & 0x00ff) + amt
  const B = (num & 0x0000ff) + amt

  return `#${(
    0x1000000 +
    (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 +
    (G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 +
    (B < 255 ? (B < 1 ? 0 : B) : 255)
  )
    .toString(16)
    .slice(1)}`
}

/**
 * 加暗颜色
 * @param {string} color 颜色值
 * @param {number} percent 百分比
 * @returns {string} 处理后的颜色值
 */
function darken(color, percent) {
  const num = parseInt(color.replace('#', ''), 16)
  const amt = Math.round(2.55 * percent)
  const R = (num >> 16) - amt
  const G = ((num >> 8) & 0x00ff) - amt
  const B = (num & 0x0000ff) - amt

  return `#${(
    0x1000000 +
    (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 +
    (G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 +
    (B < 255 ? (B < 1 ? 0 : B) : 255)
  )
    .toString(16)
    .slice(1)}`
}

/**
 * 生成主题色相关的颜色变量
 * @param {string} primary 主色
 * @returns {object} 颜色变量对象
 */
function generateColors(primary) {
  const colors = {
    '--el-color-primary-light-9': lighten(primary, 90),
    '--el-color-primary-light-8': lighten(primary, 80),
    '--el-color-primary-light-7': lighten(primary, 70),
    '--el-color-primary-light-5': lighten(primary, 50),
    '--el-color-primary-light-3': lighten(primary, 30),
    '--el-color-primary-dark-2': darken(primary, 20),
    '--el-color-primary-dark-3': darken(primary, 30),
    '--el-color-primary-dark-5': darken(primary, 50),
    '--el-color-primary-dark-7': darken(primary, 70),
    '--el-color-primary-dark-8': darken(primary, 80),
    '--el-color-primary-dark-9': darken(primary, 90)
  }
  return colors
}

/**
 * 动态设置 Element Plus 主题色
 * @param {string} themeColor 主题色
 */
export function setThemeColor(themeColor) {
  if (!themeColor) return

  // 使用 Element Plus 提供的 CSS 变量修改主题色
  const html = document.documentElement
  html.style.setProperty('--el-color-primary', themeColor)

  // 计算并设置主题色的浅色变量
  const colors = generateColors(themeColor)
  Object.keys(colors).forEach((key) => {
    html.style.setProperty(key, colors[key])
  })

  // 保存到 localStorage
  localStorage.setItem('theme-color', themeColor)
}

/**
 * 切换暗色模式
 * @param {boolean} isDark 是否为暗色模式
 */
export function toggleDarkMode(isDark) {
  const html = document.documentElement
  if (isDark) {
    html.classList.add('dark')
    localStorage.setItem('dark-mode', 'true')
  } else {
    html.classList.remove('dark')
    localStorage.setItem('dark-mode', 'false')
  }
}

/**
 * 初始化主题
 */
export function initTheme() {
  // 初始化主题色
  const savedColor = localStorage.getItem('theme-color')
  if (savedColor) {
    setThemeColor(savedColor)
  }

  // 初始化暗色模式
  const isDark = localStorage.getItem('dark-mode') === 'true'
  toggleDarkMode(isDark)
}
